package com.jt.aop;

import com.jt.anno.CacheFind;
import com.jt.util.ObjectMapperUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.ShardedJedis;

import java.util.Arrays;

@Component
@Aspect
public class RedisAspect {

    @Autowired
    private JedisCluster jedis;

    /*@Pointcut("@annotation(com.jt.anno.CacheFind)")
    public void doFind(){}*/

    @Around("@annotation(cacheFind)")
    public Object around(ProceedingJoinPoint jp,CacheFind cacheFind){
       String key = cacheFind.key();
        Object[] array = jp.getArgs();
        key+="::"+ Arrays.toString(array);
        Object result=null;
        if(jedis.exists(key)){
            String json = jedis.get(key);
            //获取方法签名
            MethodSignature method = (MethodSignature) jp.getSignature();
            //获取方法返回值对象
            Class tagerClass = method.getReturnType();
            Object obj = ObjectMapperUtil.toObject(json,tagerClass);
            return obj;
        }else {
            try {
                result=jp.proceed();
                String json = ObjectMapperUtil.toJson(result);
                if(cacheFind.seconds()>0){
                    jedis.setex(key,cacheFind.seconds(),json);
                }else {
                    jedis.set(key,json);
                }
                return  result;
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                throw new RuntimeException(throwable);
            }
        }

    }
}
